from django.shortcuts import render

# Create your views here.
from django.contrib.auth import login, logout, authenticate
from django.views.decorators.http import require_POST
from .forms import LoginForm
from django.http import JsonResponse
from utils import restful


@require_POST
def login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        password = form.cleaned_data.get('password')
        remember = form.cleaned_data.get('remember')
        user = authenticate(request, username=telephone, password=password)
        if user:
            if user.is_active:
                login(request, user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)

                return restful.ok()
            else:

                return restful.unauth_error('您的账号已经被冻结')
                # JsonResponse( {"code": 405, 'message': '您的账号已经被冻结了', 'data': ""}, json_dumps_params = {'ensure_ascii': False})
        else:
            return restful.params_error('手机号或者密码错误')

            #JsonResponse(                {"code": 400, 'message': '手机号或者密码错误', 'data': ""}, json_dumps_params={'ensure_ascii': False})
    else:
        return restful.params_error(form.get_errors())

        #  JsonResponse(
        #     {"code": 400, 'message': '表单验证错误', 'data': form.get_errors()}, json_dumps_params={'ensure_ascii': False})
